<template>
	<view class="container">
		<t-cropper mode="fixed" :imageUrl="imageUrl" :width="100" :height="100" :delay="150" @cancel="onCancel"
		  :radius="50"
			@confirm="onConfirm" ></t-cropper>
		<view class="userImg" style="padding-top:20rpx;">
			<image class="logo" :src="imgUrl(info.avatar)" v-if="info.avatar"
				style="width: 200rpx; height: 200rpx;border-radius:50%;" @click="selectFile">
			</image>
			<image class="logo" src="@/static/img/logo.png" v-else @click="selectFile"
				style="width: 200rpx; height: 200rpx;border-radius:50%;position:relative;">
			</image>
			<!-- {{imgUrl(info.avatar)}} -->
			<!-- <qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop"></qf-image-cropper> -->
			<!-- <uv-avatar @click="chooseMessageFile" :src="imgUrl(info.avatar)" size="100"></uv-avatar> -->
			<!-- <uv-upload style="width: 50rpx; height: 50rpx;" :action="uploadAction" @success="onUploadSuccess"></uv-upload> -->
		</view>
		<view class="bgWrite">
			<view class="userEditForm">
				<uv-form labelPosition="left" :model="info" ref="form1">
					<uv-form-item label="昵称" label-width="90" prop="userInfo.name" :borderBottom="false" ref="item1">
						<uv-input v-model="info.name" border="none" fontSize="28rpx" color="#909090"></uv-input>
					</uv-form-item>
					<uv-form-item label="手机号" label-width="90" prop="userInfo.phone" :borderBottom="false" ref="item1">
						<uv-input v-model="info.account" border="none" color="#909090" fontSize="28rpx"></uv-input>
					</uv-form-item>
					<uv-form-item label="性别" label-width="90" prop="userInfo.sex" :borderBottom="false"
						@click="picker.open()" ref="item1">
						<text class="sex">{{sex||'请选择性别'}}</text>
						<uv-icon slot="right" name="arrow-right" size="13" color='#999'></uv-icon>
					</uv-form-item>
					<uv-form-item label="职业" label-width="90" prop="userInfo.sex" :borderBottom="false"
						@click="pickerj.open()" ref="item1">
						<text class="sex">{{job||'请选择职业'}}</text>
						<uv-icon slot="right" name="arrow-right" size="13" color='#999'></uv-icon>
					</uv-form-item>
					<uv-form-item label="学历" label-width="90" prop="userInfo.sex" :borderBottom="false"
						@click="pickerS.open()" ref="item1">
						<text class="sex">{{study||'请选择学历'}}</text>
						<uv-icon slot="right" name="arrow-right" size="13" color='#999'></uv-icon>
					</uv-form-item>
					<uv-form-item label="生日" label-width="90" prop="userInfo.sex" :borderBottom="false"
						@click="datetimePicker.open()" ref="item1">
						<text class="sex">{{birth||'请选择生日'}}</text>
						<uv-icon slot="right" name="arrow-right" size="13" color='#999'></uv-icon>
					</uv-form-item>
				</uv-form>
				<uv-picker ref="picker" :columns="[columns]" @confirm="conSex"></uv-picker>
				<uv-picker ref="pickerj" :columns="[jobs]" @confirm="conJob"></uv-picker>
				<uv-picker ref="pickerS" :columns="[studys]" @confirm="conSty"></uv-picker>
				<uv-datetime-picker ref="datetimePicker" v-model="values" mode="date" @confirm="conBith"
					:minDate="87524800000">
				</uv-datetime-picker>
				<button class="blueBtn" @click="submit()">提交</button>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onReady, onShow, onLoad } from '@dcloudio/uni-app';
	import { ref, watch } from 'vue';
	import { http, apiPath, http_upload } from '@/common/http/index';
	import { toast, imgUrl } from '@/utils/fun';
	import { reactive, toRefs } from "vue";
	const model = reactive({
		imageUrl: "",
		resultUrl: [],
	});
	const [name, phone, remark,product_id,attr_id] = [ref(), ref(), ref(), ref(), ref()];
	onLoad(e => {
		if (e.name) {
			name.value = e.name;
			phone.value = e.phone;
			remark.value = e.remark;
			product_id.value = e.product_id;
			attr_id.value = e.attr_id;
		}
		get_info();
	});
	const { resultUrl, imageUrl } = toRefs(model);
	// 使用uni.compressImage压缩图片
	const compressImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: "original",
			success: (res) => {
				console.log("original", res);
				//  示例：防止大图片文件的Image无法直接临时路径显示图片
				uni.showLoading({
					title: "处理中...",
					mask: true,
				});
				// 使用uni.compressImage压缩图片
				uni.compressImage({
					src: res.tempFilePaths[0],
					quality: 80, // 压缩质量
					success: (compressRes) => {
						model.imageUrl = compressRes.tempFilePath;
					},
					fail: (err) => {
						console.error("图片压缩失败：", err);
					},
					complete: () => {
						uni.hideLoading(); // 关闭loading
					},
				});
			},
		});
	};
	// 使用默认压缩方式
	const defaultCompressImage = () => {
		uni.chooseImage({
			count: 1,
			sizeType: 'original ',
			success: (res) => {
				model.imageUrl = res.tempFilePaths[0];
			},
		});
	};
	const chooseMessageFile = () => {
			uni.chooseImage({
				count: 1,
				sizeType: 'original ',
				sourceType: ['album'],
				success: (res) => {
					const filePath = res.tempFilePaths[0]
					upFileApi(filePath);
				}
			})
		}
	const selectFile = () => {
		defaultCompressImage();
	};

	// 关闭裁剪
	const onCancel = () => {
		model.imageUrl = "";
	};
	// 接口上传图片
	const upFileApi = (filePath) => {
		http_upload({
			url: '/api/v1/upload/local/image',
			filePath: filePath
		}).then((res : any) => {
			info.value.avatar = res.data
			model.imageUrl = "";
		}).catch(err => {
			console.log('err', err);
		})
	}
	// 裁剪确认
	const onConfirm = (res) => {
		// 设置url的值，显示控件
		// const params = {
		// 	id: new Date().getTime(),
		// 	url: res.tempFilePath,
		// };
		upFileApi(res.tempFilePath);
		// model.resultUrl.push(params);
		// model.imageUrl = "";
	};
	// 预览图片
	const prviewImgae = (index, url) => {
		uni.previewImage({
			current: index, // 当前资源下标
			urls: [url],
		});
	};
	const info = ref({})
	const get_info = async () => {
		const res = await http.get('/api/v1/user/info')
		info.value = res.data;
		sex.value = getSex(info.value.sex);
		if (info?.value?.birthday) {
			birth.value = info?.value?.birthday.substring(0, 10) || '';
		}
		job.value = getJob(info.value.occupation);
		study.value = getSty(info.value.education);
	}

	const values = ref(Number(new Date()));
	console.log("111111111111", values.value);
	const [picker, pickerj, pickerS, datetimePicker, loading, showSex, sex, job, study, birth] = [ref(), ref(), ref(), ref(), ref(false), ref(false), ref(), ref(), ref(), ref()]
	const [columns, jobs, studys] = [ref(['男', '女']), ref(['学生', '自由职业', '公务员', '公司职员', '企业高管']),
	ref(['中专及以下', '大专', '本科', '研究生'])];
	const submit = () => {
		loading.value = true;
		const params = {
			avatar: info.value.avatar,
			name: info.value.name,
			sex: getSex(sex.value),
			birthday: birth.value,
			occupation: getJob(job.value),
			education: getSty(study.value),
		};
		http
			.post(`/api/v1/user/update`, params, { custom: { loading: true } })
			.then((res : any) => {
				console.log('res', res);
				if(name.value){
					uni.redirectTo({ url: '/pages/lesson/lessonOrder?name='+name.value+'&phone='+
					 phone.value+'&remark='+remark.value+'&product_id='+product_id.value+'&attr_id='+attr_id.value})
				}else{
						toast('修改成功');
					setTimeout(() => {
						uni.navigateBack()
						loading.value = false;
					}, 2000);
				}
			
			})
			.catch((err) => {
				setTimeout(() => {
					loading.value = false;
				});
			});
	};
	//确定男女
	const conSex = (e) => {
		sex.value = e.value[0];
		console.log("11111", sex.value);
	}
	const handleCrop = (e) => {
		console.log("11111111", e)
		uni.previewImage({
			urls: [e.tempFilePath],
			current: 0
		});
	}
	//学历
	const getSty = (e) => {
		if (e == 1) {
			return '中专及以下';
		} else if (e == 2) {
			return '大专';
		} else if (e == 3) {
			return '本科 ';
		} else if (e == 4) {
			return '研究生 ';
		} else if (e == '中专及以下') {
			return 1;
		} else if (e == '大专') {
			return 2;
		} else if (e == '本科') {
			return 3;
		} else if (e == '研究生') {
			return 4;
		}
		return '请选择学历'
	}
	const getJob = (e) => {
		if (e == 1) {
			return '学生';
		} else if (e == 2) {
			return '自由职业';
		} else if (e == 3) {
			return '公务员 ';
		} else if (e == 4) {
			return '公司职员 ';
		} else if (e == 5) {
			return '企业高管 ';
		} else if (e == '学生') {
			return 1;
		} else if (e == '自由职业') {
			return 2;
		} else if (e == '公务员') {
			return 3;
		} else if (e == '公司职员') {
			return 4;
		} else if (e == '企业高管') {
			return 5;
		}
		return '请选择职业'
	}
	//判断男女
	const getSex = (e) => {
		if (e == 1) {
			return '男';
		} else if (e == 2) {
			return '女';
		} else if (e == '女') {
			return 2;
		} else if (e == '男') {
			return 1;
		}
		return '未知';
	}
	//确定职业
	const conJob = (e) => {
		job.value = e.value[0];
	}
	//确定学历
	const conSty = (e) => {
		study.value = e.value[0];
	}
	//确认生日
	const conBith = (e) => {
		const date = ref(new Date(e.value));
		const year = ref(date.value.getFullYear());
		const month = ref(String(date.value.getMonth() + 1).padStart(2, '0')); // 月份从0开始
		const day = ref(String(date.value.getDate()).padStart(2, '0'));
		birth.value = `${year.value}-${month.value}-${day.value}`;

	}
</script>

<style lang="scss" scoped>
	.container {
		background: #fff;
		min-height: 95vh;

	}

	.blueBtn {
		width: 550rpx;
		height: 90rpx;
		background: #31C0ED;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		font-size: 26rpx;
		color: #fff;
		width: 560rpx;
		line-height: 90rpx;
		position: fixed;
		bottom: 5%;
		left: 0;
		right: 0;
	}

	.sex {
		font-size: 26rpx;
		color: #909090;
	}

	.userImg {
		position: relative;
		width: 200rpx;
		height: 200rpx;
		margin: 0 auto 40rpx;
	}

	.uv-upload {
		position: absolute;
		right: 10rpx;
		bottom: 30rpx;
	}

	::v-deep .uv-upload__button {
		background-color: #fff;
		border: 1px solid #ccc !important;
		width: 70rpx !important;
		height: 70rpx !important;
		border-radius: 50% !important;
	}

	.userEditForm {
		padding: 30rpx 60rpx;
	}
</style>